<template>
  <!-- <div style="width: 100%;height: 40px;background-color: rgba(0,255,82,0.15);color: #1b9f26;line-height: 40px;padding: 0 20px;
  margin-bottom: 20px;font-size: 14px;text-align: center;border:1px solid rgba(27,159,38,0.32)">当前为演示数据</div> -->
  <div class="dashboard-title">书来书往数据统计看板</div>
  <div class="row-title-container">
    <div class="row-title">基础情况</div>
  </div>
  <el-row :class="prefixCls" :gutter="20" justify="space-between">
    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--peoples p-16px inline-block rounded-6px`"
            >
              <Icon :size="40" icon="svg-icon:shuji"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">
              漂入书籍总量
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.bookTotalCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--message p-16px inline-block rounded-6px`">
              <Icon :size="40" icon="svg-icon:apply"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">
              漂入漂出申请总量
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.applyTotalCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--peoples p-16px inline-block rounded-6px`"
            >
              <Icon :size="40" icon="svg-icon:users"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">
              会员总数
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.userTotalCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>

    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--message p-16px inline-block rounded-6px`">
              <Icon :size="40" icon="svg-icon:hyyh"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`">
              月活用户量（近30天）
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.lifeUserCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <div class="row-title-container">
    <div class="row-title">漂入漂出</div>
    <div style="color: #666">
      时间范围：
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        @change="onDateRangeChange"
        class="date-picker-fixed"
      />
    </div>
  </div>
  <el-row :class="prefixCls" :gutter="20" justify="space-between">
    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover" v-loading="loading">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--money p-16px inline-block rounded-6px`">
              <Icon :size="40" icon="svg-icon:juanru"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`"
            >漂入申请
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.inBookUserCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>

    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover" v-loading="loading">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--shopping p-16px inline-block rounded-6px`"
            >
              <Icon :size="40" icon="svg-icon:juanchu"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`"
            >漂出申请
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.outBookUserCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>
    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover" v-loading="loading">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--money p-16px inline-block rounded-6px`">
              <Icon :size="40" icon="svg-icon:send"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`"
            >漂入书籍
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.inBookCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>

    <el-col :lg="6" :md="12" :sm="12" :xl="6" :xs="24">
      <el-card class="mb-20px" shadow="hover" v-loading="loading">
        <div :class="`${prefixCls}__item flex justify-between`">
          <div>
            <div
              :class="`${prefixCls}__item--icon ${prefixCls}__item--shopping p-16px inline-block rounded-6px`"
            >
              <Icon :size="40" icon="svg-icon:member_point"/>
            </div>
          </div>
          <div class="flex flex-col justify-between">
            <div :class="`${prefixCls}__item--text text-16px text-gray-500 text-right`"
            >漂出书籍
            </div>
            <CountTo
              :duration="2600"
              :end-val="statisData?.outBookCount || 0"
              :start-val="0"
              class="text-right text-20px font-700"
            />
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="20" justify="space-between">
    <!-- 书籍漂入趋势 -->
    <el-col :lg="12" :md="24" :sm="24" :xl="14" :xs="24">
      <el-card class="mb-20px" shadow="hover" v-loading="loading">
        <Echart :height="240" :options="lineOptionsData"/>
      </el-card>
    </el-col>
    <!-- 新增用户趋势 -->
    <el-col :lg="12" :md="24" :sm="24" :xl="14" :xs="24">
      <el-card class="mb-20px" shadow="hover" v-loading="loading">
        <Echart :height="235" :options="barOptionsData"/>
      </el-card>
    </el-col>

  </el-row>
</template>
<script lang="ts" setup>
import {set} from 'lodash-es'
import {EChartsOption} from 'echarts'
import {useDesign} from '@/hooks/web/useDesign'
import type {AnalysisTotalTypes} from '../../Home/types'
import {barOptions, lineOptions, pieOptions} from '../../Home/echarts-data'
import {LwBookApi, StatisDataVO} from '@/api/bk/lwbook'

defineOptions({name: 'Home2'})

const {t} = useI18n()
const loading = ref(true)
const {getPrefixCls} = useDesign()
const prefixCls = getPrefixCls('panel')
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 时间范围选择器
const dateRange = ref<[string, string]>()

// 初始化时间范围为30天前到今天
const initDateRange = () => {
  const today = new Date()
  const thirtyDaysAgo = new Date()
  thirtyDaysAgo.setDate(today.getDate() - 30)

  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  dateRange.value = [formatDate(thirtyDaysAgo), formatDate(today)]
}

// 时间范围变化事件
const onDateRangeChange = async () => {
  loading.value = true
  await getAllApi()
}

// 统计数据
const statisData = ref<StatisDataVO>({
  bookTotalCount: 0,
  applyTotalCount: 0,
  inBookCount: 0,
  outBookCount: 0,
  userTotalCount: 0,
  lifeUserCount: 0,
  inBookUserCount: 0,
  outBookUserCount: 0,
  newBookChart: {xdata: [], ydata: []},
  newUserChart: {xdata: [], ydata: []}
})

let totalState = reactive<AnalysisTotalTypes>({
  users: 0,
  messages: 0,
  moneys: 0,
  shoppings: 0
})

// 获取统计数据
const getStatisData = async () => {
  try {
    const params: any = {}
    if (dateRange.value && dateRange.value.length === 2) {
      // 为开始日期添加 00:00:00，为结束日期添加 23:59:59
      params.createTime = [
        dateRange.value[0] + ' 00:00:00',
        dateRange.value[1] + ' 23:59:59'
      ]
    }

    const response = await LwBookApi.getStatisData(params)
    console.log('API响应数据:', response) // 添加调试日志
    // 根据实际API返回结构调整数据赋值
    if (response && response.data) {
      // 如果response.data是包装后的数据
      if (response.data.code === 0) {
        statisData.value = response.data.data
      } else {
        // 如果response.data直接是统计数据
        statisData.value = response.data
      }
    } else if (response && typeof response === 'object' && response.bookTotalCount !== undefined) {
      // 如果response直接是统计数据对象
      statisData.value = response
    }
    console.log('统计数据已更新:', statisData.value) // 添加调试日志
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const getCount = async () => {
  const data = {
    users: 102400,
    messages: 81212,
    moneys: 9280,
    shoppings: 13600
  }
  totalState = Object.assign(totalState, data)
}

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    {value: 335, name: 'analysis.directAccess'},
    {value: 310, name: 'analysis.mailMarketing'},
    {value: 234, name: 'analysis.allianceAdvertising'},
    {value: 135, name: 'analysis.videoAdvertising'},
    {value: 1548, name: 'analysis.searchEngines'}
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  set(pieOptionsData, 'series.data', data)
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 月新增用户趋势
const getWeeklyUserActivity = async () => {
  if (statisData.value && statisData.value.newUserChart && statisData.value.newUserChart.xdata.length > 0) {
    set(barOptionsData, 'xAxis.data', statisData.value.newUserChart.xdata)
    set(barOptionsData, 'series', [
      {
        name: '新增用户',
        data: statisData.value.newUserChart.ydata,
        type: 'bar'
      }
    ])
  } else {
    // 默认数据
    const data = [
      {value: 13253, name: 'analysis.monday'},
      {value: 34235, name: 'analysis.tuesday'},
      {value: 26321, name: 'analysis.wednesday'},
      {value: 12340, name: 'analysis.thursday'},
      {value: 24643, name: 'analysis.friday'},
      {value: 1322, name: 'analysis.saturday'},
      {value: 1324, name: 'analysis.sunday'}
    ]
    set(
      barOptionsData,
      'xAxis.data',
      data.map((v) => t(v.name))
    )
    set(barOptionsData, 'series', [
      {
        name: t('analysis.activeQuantity'),
        data: data.map((v) => v.value),
        type: 'bar'
      }
    ])
  }
}

const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

// 月新漂入书籍趋势
const getMonthlySales = async () => {
  // 设置图表标题
  set(lineOptionsData, 'title.text', '书籍漂入趋势')
  if (statisData.value && statisData.value.newBookChart && statisData.value.newBookChart.xdata.length > 0) {
    set(lineOptionsData, 'xAxis.data', statisData.value.newBookChart.xdata)
    set(lineOptionsData, 'series', [
      {
        name: '新漂入书籍',
        smooth: true,
        type: 'line',
        data: statisData.value.newBookChart.ydata,
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      }
    ])
  }
}

const getAllApi = async () => {
  await getStatisData() // 先获取统计数据
  await Promise.all([getCount(), getUserAccessSource()])
  // 在统计数据加载完成后再执行图表相关的方法
  await Promise.all([getWeeklyUserActivity(), getMonthlySales()])
  loading.value = false
}

// 初始化
initDateRange()
getAllApi()
</script>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-panel;

.dashboard-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  text-align: center;
  margin-bottom: 20px;
  padding: 16px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;

  &::after {
    content: '';
    position: absolute;
    bottom: 8px;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 3px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 2px;
  }
}

.card-header {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.#{$prefix-cls} {
  &__item {
    &--peoples {
      color: #40c9c6;
    }

    &--message {
      color: #36a3f7;
    }

    &--money {
      color: #f4516c;
    }

    &--shopping {
      color: #34bfa3;
    }

    &:hover {
      :deep(.#{$namespace}-icon) {
        color: #fff !important;
      }

      .#{$prefix-cls}__item--icon {
        transition: all 0.38s ease-out;
      }

      .#{$prefix-cls}__item--peoples {
        background: #40c9c6;
      }

      .#{$prefix-cls}__item--message {
        background: #36a3f7;
      }

      .#{$prefix-cls}__item--money {
        background: #f4516c;
      }

      .#{$prefix-cls}__item--shopping {
        background: #34bfa3;
      }
    }
  }
}

.row-title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.row-title {
  padding: 0 10px;
  font-size: 16px;
  color: #6b6b6b;
  border-left: 3px solid rgba(9, 85, 255, 0.79);
}

.date-picker-fixed {
  width: 240px !important;
  flex-shrink: 0;
}
</style>
